import router from "@/routers/index";
import { LOGIN_URL } from "@/config";
import { RouteRecordRaw } from "vue-router";
import { ElNotification } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue");

/**
 * @description 初始化动态路由
 */
export const initDynamicRouter = async () => {
  const userStore = useUserStore();
  const authStore = useAuthStore();

  try {
    // 1.获取菜单列表 && 按钮权限列表
    await authStore.getAuthMenuList();
    await authStore.getAuthButtonListFlat();

    // 2.检查数据是否有效
    if (!authStore.authMenuListGet.length) {
      ElNotification({
        title: "无权限访问",
        message: "当前账号无任何菜单权限，请联系系统管理员！",
        type: "warning",
        duration: 3000
      });
      userStore.setToken("");
      router.replace(LOGIN_URL);
      return Promise.reject("No permission");
    }

    // 3.注册路由（关键修改）
    authStore.flatMenuListGet.forEach(item => {
      // 确保处理所有层级的路由
      if (item.children) {
        item.children.forEach(child => {
          registerRoute(child); // 注册子路由
        });
      }
      registerRoute(item); // 注册父路由
    });
  } catch (error) {
    console.error("路由初始化失败:", error);
    userStore.setToken("");
    router.replace(LOGIN_URL);
    return Promise.reject(error);
  }
};

// 辅助函数：单独注册路由
function registerRoute(route: any) {
  if (!route.component) return;

  const routeConfig: RouteRecordRaw = {
    path: route.path,
    name: route.name,
    component: modules[`/src/views${route.component}.vue`],
    meta: route.meta
  };

  if (route.meta?.isFull) {
    router.addRoute(routeConfig);
  } else {
    router.addRoute("layout", routeConfig);
  }
}
